package cn.kailangtu.myapplication.camera;

import android.content.Context;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceView;

import java.nio.ByteBuffer;


//集成了AvcDecoder解码功能的SurfaceView
//使用AvcDecoder，则需要手动绑定一个SurfaceView
public class AvcPlayer extends SurfaceView {

    MediaCodec mediaCodec;

    Callback callback;

    int width;
    int height;

    boolean playing = false;

    public AvcPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void init(int width, int height, Callback callback) {
        this.callback = callback;
        this.width = width;
        this.height = height;
    }

    private int configureMediaCodec() {
        int flag = 0;
        try {
            mediaCodec = MediaCodec.createDecoderByType("video/avc");
            MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height);
            mediaCodec.configure(mediaFormat, getHolder().getSurface(), null, 0);
            mediaCodec.start();
        } catch (Exception e) {
            Log.e("MediaCodec初始化异常：", e.toString());
            flag = -1;
        }
        return flag;
    }

    public void decodeNalu(byte[] nalu) {
        if (!playing) return;

        ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
        int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1);
        if (inputBufferIndex < 0)
            return;

        ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
        inputBuffer.clear();
        inputBuffer.put(nalu, 0, nalu.length);
        mediaCodec.queueInputBuffer(inputBufferIndex, 0, nalu.length, 0, 0);

        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 100);
        while (outputBufferIndex >= 0) {
            mediaCodec.releaseOutputBuffer(outputBufferIndex, true);
            outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
        }

        if (callback != null)
            callback.onFrameUpdate(nalu);
    }

    public int startPreview() {
        int flag = configureMediaCodec();
        if (flag == 0) {
            playing = true;
        }
        return flag;
    }

    public void stopPreview() {
        try {
            playing = false;
            mediaCodec.stop();
            mediaCodec.release();
            mediaCodec = null;
        }
        catch(Exception e)
        {
            Log.e("关闭预览异常", e.toString());
        }
    }

    public interface Callback {

        void onFrameUpdate(byte[] frame);
    }
}

